
package com.xy.controller;

import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author xxy
 * @date 2022/1/7 16:07
 */
@Slf4j
@RestController
@RequestMapping("use-redis-dcs-lock-05")
public class UseRedisDCSLock05 {

    private final StringRedisTemplate redisTemplate;
    private final RedissonClient redissonClient;

    public UseRedisDCSLock05(StringRedisTemplate redisTemplate,
                             RedissonClient redissonClient) {
        this.redisTemplate = redisTemplate;
        this.redissonClient = redissonClient;
    }

    @GetMapping("test-use-redis-dcs-lock")
    public Object testUseRedisDCSLock() {
        // 获取锁
        RLock rLock = redissonClient.getLock("lock");
        // 加锁
        rLock.lock(10, TimeUnit.SECONDS);
        List<String> dbList = null;
        try {
            dbList = dataList();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }
        return dbList;
    }


    private List<String> dataList() {
        List<String> dataList = new ArrayList<>();
        String[] data = {"a", "b", "c"};
        List<String> list = Arrays.asList(data);
        dataList.addAll(list);
        return dataList;
    }


}
